package com.kintreda.service.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kintreda.common.config.R;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import com.kintreda.common.mybatis.entity.SysAdmin;
import com.kintreda.common.mybatis.model.BasePageModel;
import com.kintreda.common.mybatis.service.ISysAdminService;
import com.kintreda.common.oauth.annotation.SetLog;
import com.kintreda.common.oauth.jwt.JwtUtils;
import com.kintreda.tools.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/platform/admin")
@Api(tags = "管理员")
public class AdminController {

    @Autowired
    private ISysAdminService iSysAdminService;

    @ApiOperation(value = "管理员管理")
    @GetMapping("/list")
    public R<IPage<SysAdmin>> admin(BasePageModel param){
        IPage<SysAdmin> sysAdminIPage = iSysAdminService.listByManager(param);
        return R.ok(sysAdminIPage);
    }

    @ApiOperation(value = "保存管理员信息")
    @PostMapping("/save")
    @SetLog("添加或修改管理员")
    public R<Boolean> save(@Valid @RequestBody SysAdmin param){
        if (ObjectUtils.isNotEmpty(param.getAdmId())){
            SysAdmin admin = iSysAdminService.getById(param.getAdmId());
            if (!admin.getPassword().equals(param.getPassword())){
                param.setPassword(CommonUtils.getPwd(param.getPassword()));
            }
        }else{
            param.setPassword(CommonUtils.getPwd(param.getPassword()));
        }
        //检查账号重复性
        SysAdmin login = iSysAdminService.login(param.getUsername(), null);
        if (ObjectUtils.isNotEmpty(login) && ObjectUtils.isEmpty(param.getAdmId()) || ObjectUtils.isNotEmpty(login) && ObjectUtils.isNotEmpty(param.getAdmId()) && !login.getAdmId().equals(param.getAdmId())){
            throw new CommonBaseException(CommonBaseErrorCode.ACCOUNT_REPETITION);
        }
        iSysAdminService.saveOrUpdate(param);
        return R.ok();
    }

    @ApiOperation(value = "删除管理员")
    @DeleteMapping("/del/{admId}")
    @SetLog("删除管理员")
    public R<Boolean> del(@PathVariable Integer admId){
        iSysAdminService.removeById(admId);
        return R.ok();
    }


}
